package com.os.ops;


import com.os.feign.DataService;
import feign.Response;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

/**
 *
 * 临时对象传输
 * @author zhaozhikai
 * @date 2023/12/25 21:19
 */
@Slf4j
public class TempPutStream extends OutputStream {
    private DataService dataService;

    //服务的地址
    private URI server;

    //临时id
    private  String uuid;

    public TempPutStream(URI server,DataService dataService, String hash, int size) {
        this.server = server;
        //远程请求调用，创建 临时对象，
        this.dataService = dataService;
        Response post = this.dataService.post(server, size, hash);
        // 返回uuid this.uuid = response
        this.uuid = post.body().toString();
        log.info(uuid);
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        //远程请求传输数据
        dataService.patch(server,uuid,b);
    }

    @Override
    public void write(int b) throws IOException {
        write(new byte[]{(byte) b}, 0,1);
    }

    public void commit(boolean good){
        //请求是否需要删除 或者转正文件
        if(good){
            dataService.put(server,uuid);
        }else{
            dataService.delete(server,uuid);
        }
    }
}
